package check

import (
	"auto/base"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

func GetPic(url string, name string) (litpic string, err error) {
	exist, _ := pathExists(base.Config.WebPath)
	if !exist {
		err = errors.New("站点目录错误")
		return
	}
	filepath := fmt.Sprintf("/uploads/dianpu/%v.jpg", name)
	out, err := os.Create(base.Config.WebPath + filepath)
	if err != nil {
		return
	}
	defer out.Close()
	resp, err := http.Get(url)
	if err != nil {
		return
	}
	defer resp.Body.Close()
	pix, err := ioutil.ReadAll(resp.Body)
	_, err = io.Copy(out, bytes.NewReader(pix))
	litpic = filepath
	return

}

func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
